

function widget_formInit(domNode)
{
	window.onbeforeunload =	function() {
		var ask = false;
		var message = '';
		jQuery('.widget-form').each(function () {
			if (this.checkUnsaved && this.isUnsaved) {
				message += window.babAddonWidgets.getMetadata(jQuery(this).attr('id')).unsavedMessage + '\n' || '';
				ask = true;
			}
		});
		if (ask) {
			return message;
		}
	};


	var validate = true;
	jQuery(domNode).find('.widget-form')

	.each(
		function() {
			this.isUnsaved = false;
			if (window.babAddonWidgets.getMetadata(jQuery(this).attr('id')).checkUnsaved) {
				this.checkUnsaved = true;
				var form = this;
				jQuery(this).find('input, textarea, select').change(function () {
					form.isUnsaved = true;
				});
			}
		}
	)
	
	.submit(
		function(event) {

			if (!window.babAddonWidgets.validate) {
				return true;
			}
			var canSubmit = true;
			var errorMessages = [];
			jQuery(this).find('.widget-input-mandatory').not('.widget-displaymode').each(function() {
				if (jQuery(this).val() === '') {
					jQuery(this).css('border', '1px solid red');
					if (window.babAddonWidgets.getMetadata(jQuery(this).attr('id')).mandatoryErrorMessage)
					{
						errorMessages.push(window.babAddonWidgets.getMetadata(jQuery(this).attr('id')).mandatoryErrorMessage);
					}
					canSubmit = false;
				} else {
					jQuery(this).css('border', '');
				}
			}
			);
			jQuery(this).find('.widget-timepicker').each(function() {
				var time = jQuery(this).val();
				if (time === '') {
					return 0;
				}
				var values = time.split(':');
				if (values.length != 2) {
					jQuery(this).css('border', '1px solid red');
					errorMessages.push("Format d'heure non valide.");
					canSubmit = false;
				} else {
					var hours = parseInt(values[0]);
					var minutes = parseInt(values[1]);
					if (isNaN(hours) || isNaN(minutes) || hours < 0 || hours > 23 || minutes < 0 || minutes > 59 ) {
						jQuery(this).css('border', '1px solid red');
						errorMessages.push("Format d'heure non valide.");
					} else {
						jQuery(this).css('border', '');
					}
				}
			}
			);
			if (errorMessages.length > 0) {
				alert(errorMessages.join("\n"));
			}

			return canSubmit;
		}
	);



	jQuery(domNode).find('.widget-form .widget-submitbutton').click(
		function(event) {

			var form = jQuery(this).parents('form').get(0);
			form.isUnsaved = false;

			if (jQuery(this).hasClass('widget-submitbutton-validate')) {
				window.babAddonWidgets.validate = true;
			} else {
				window.babAddonWidgets.validate = false;
			}
		}
	);



	jQuery(domNode).find('.widget-form').find('.widget-autosubmitonchange').change(function () {
		jQuery(this).parents('form').submit();
	}
	);

}


window.bab.addInitFunction(widget_formInit);


